package com.mock.ai.controller;

import com.mock.ai.repository.ChatHistoryRepository;
import com.mock.ai.utils.TTSUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.content.Media;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClientWithTools;

    private final ChatHistoryRepository chatHistoryRepository;

    @RequestMapping(value = "/tts")
    public String tts(@RequestParam String prompt) {
        // 1.保存会话id
        String content = chatClientWithTools.prompt()
                .user(prompt)
                .call()
                .content();
        try {
            TTSUtils.tts(content);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return content;
    }

    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
    public Flux<String> chat(
            @RequestParam("prompt") String prompt,
            @RequestParam("chatId") String chatId,
            @RequestParam(value = "files", required = false) List<MultipartFile> files) {
        // 1.保存会话id
        chatHistoryRepository.save("chat", chatId);
        // 2.请求模型
        if (files == null || files.isEmpty()) {
            // 没有附件，纯文本聊天
            return textChat(prompt, chatId);
        } else if (files.get(0).getOriginalFilename().endsWith(".txt")) {
            // 有附件，多模态聊天
            return multiModalChatText(prompt, chatId, files);
        } else {
            // 有附件，多模态聊天
            return multiModalChat(prompt, chatId, files);
        }

    }

    private Flux<String> multiModalChat(String prompt, String chatId, List<MultipartFile> files) {
//        // 1.解析多媒体
        List<Media> medias = files.stream()
                .map(file -> new Media(
                                MimeType.valueOf(Objects.requireNonNull(file.getContentType())),
                                file.getResource()
                        )
                )
                .toList();
        // 2.请求模型
        return chatClientWithTools.prompt()
//                .user(p -> p.text(prompt).text(convertToResource(files).get(0)).media(medias.toArray(Media[]::new)))
                // 图片，语音，视频 使用media，不能将文件转换成文字
                .user(p -> p.text(prompt).media(medias.toArray(Media[]::new)))
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();
    }

    private Flux<String> multiModalChatText(String prompt, String chatId, List<MultipartFile> files) {
        return chatClientWithTools.prompt()
                // 文本文件使用text，将.txt文件转换成文字
                .user(p -> p.text(prompt).text(convertToResource(files).get(0)))
                // .user(p -> p.text(prompt).media(medias.toArray(Media[]::new)))
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();
    }


    private Flux<String> textChat(String prompt, String chatId) {
        return chatClientWithTools.prompt()
                .user(prompt)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();
    }

    public List<FileSystemResource> convertToResource(List<MultipartFile> files){
        return files.stream().map(file -> {
            try {
                // 创建临时文件
                Path tempFile = Files.createTempFile("upload-", "-" + file.getOriginalFilename());
                // 将 MultipartFile 内容复制到临时文件
                Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);
                // 返回指向临时文件的 FileSystemResource
                return new FileSystemResource(tempFile.toFile()) {
                    // 重写 getFilename 以返回原始文件名
                    @Override
                    public String getFilename() {
                        return file.getOriginalFilename();
                    }
                };
            } catch (IOException e) {
                throw new RuntimeException("Failed to save MultipartFile to temp file", e);
            }
        }).collect(Collectors.toList());
    }
}
